<template>
  <div class="cg-input-number">
    <input
      ref="input"
      type="number"
      :placeholder="placeholder"
      :value="data"
      @input.stop="handleInput"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

// 定义组件名称
defineOptions({
  name: 'cg-input-number'
})

// 定义props
const props = withDefaults(
  defineProps<{
    modelValue: string | number
    placeholder: string
  }>(),
  {
    placeholder: '请输入'
  }
)

// 定义emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: string | number): void
}>()

// 组件引用
const input = ref<HTMLInputElement | null>(null)

// 响应式数据
const data = ref<string | number>(props.modelValue)

// 监听modelValue变化
watch(
  () => props.modelValue,
  (val) => {
    data.value = val
  },
  { immediate: true }
)

// 方法
const handleInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  let inputValue = target.value
  // 确保输入是数字
  if (inputValue !== '' && isNaN(Number(inputValue))) {
    return
  }
  data.value = inputValue === '' ? '' : Number(inputValue)
  emit('update:modelValue', data.value)
}
</script>

<style lang="scss">
.cg-input-number {
  padding: 0 1em;
  background: #f2f2f2;
  display: inline-block;
  input {
    background: none;
    font-size: 1em;
    line-height: 2em;
    letter-spacing: 0px;
    border: none;
    outline: unset;
    width: 100%;
    -webkit-appearance: none;
    color: #606266;
  }

  &:focus {
    outline: none;
  }
}
</style>
